package cn.amaake.magicplugin.rpc.service;

import cn.amaake.magicplugin.rpc.model.RpcInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.event.EventListener;
import org.ssssssss.magicapi.core.config.MagicConfiguration;
import org.ssssssss.magicapi.core.event.FileEvent;
import org.ssssssss.magicapi.core.event.GroupEvent;
import org.ssssssss.magicapi.core.model.Group;
import org.ssssssss.magicapi.core.service.AbstractMagicDynamicRegistry;
import org.ssssssss.magicapi.core.service.MagicResourceStorage;

import java.util.List;
import java.util.stream.Collectors;

public class RpcMagicDynamicRegistry extends AbstractMagicDynamicRegistry<RpcInfo> {


    private static final Logger logger = LoggerFactory.getLogger(RpcMagicDynamicRegistry.class);

    private DobboService dobboService;

    public RpcMagicDynamicRegistry(MagicResourceStorage<RpcInfo> magicResourceStorage,DobboService dobboService) {
        super(magicResourceStorage);
        this.dobboService = dobboService;
    }

    @EventListener(condition = "#event.type == 'rpc'")
    public void onFileEvent(FileEvent event) {
        processEvent(event);
    }

    @EventListener(condition = "#event.type == 'rpc'")
    public void onGroupEvent(GroupEvent event) {
        processEvent(event);
    }

    @Override
    public boolean register(RpcInfo entity) {
        logger.info("注册 register mapping node:{}", entity);
        logger.info(entity.isEnabled()+"");
        Group group = MagicConfiguration.getMagicResourceService().getGroup(entity.getGroupId());
        List<RpcInfo> rpcInfoList = MagicConfiguration.getMagicResourceService().listFiles(entity.getGroupId());
        List<RpcInfo> updateRpcInfoList = rpcInfoList.stream()
                .map(rpcInfo -> rpcInfo.getId().equals(entity.getId()) ? entity : rpcInfo)
                .collect(Collectors.toList());
        if(updateRpcInfoList.isEmpty()){
            updateRpcInfoList.add(entity);
        }
        dobboService.registerService(group.getPath(),entity,updateRpcInfoList);
        return super.register(entity);
    }

    @Override
    public boolean unregister(RpcInfo entity) {
        logger.info("卸载 unregister mapping node:{}", entity);
        logger.info(entity.isEnabled()+"");
        Group group = MagicConfiguration.getMagicResourceService().getGroup(entity.getGroupId());
        List<RpcInfo> rpcInfoList = MagicConfiguration.getMagicResourceService().listFiles(entity.getGroupId());
        rpcInfoList.removeIf(rpc -> rpc.getPath().equals(entity.getPath()));
        dobboService.unexport(group.getPath(),entity,rpcInfoList);
        return super.unregister(entity);
    }

}